using System;
using System.Collections;
using System.Reflection;
using System.Threading;
using System.Web;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;

namespace Sedna.Core.Controls.ExceptionHandlers
{
	/// <summary>
	/// Summary description for PopupExceptionHandler.
	/// </summary>
	public class PopupExceptionHandler: AbstractExceptionHandler 
	{
		private string errorPageUrl;
		private string errorMessageParamName;

		public string ErrorPageUrl
		{
			set { errorPageUrl = value; }
		}

		public string ErrorMessageParamName
		{
			set { errorMessageParamName = value; }
		}

		public override IActionResult HandleException(IExecutionContext executionContext, Exception exception)
		{
            if (exception is ThreadAbortException)
            {
                return new ActionResult(successStatus);
            }
		    HttpContext.Current.Response.Redirect(GetFullUrl(exception is TargetInvocationException ? exception.InnerException == null ? exception.Message : exception.InnerException.Message :
		                                                     exception.Message ));
			return new ActionResult(successStatus);
		}

		private string GetFullUrl(string message)
		{
			if (errorPageUrl.IndexOf('?')==-1)
			{
				return String.Format("{0}?{1}={2}", errorPageUrl, errorMessageParamName, message);
			}
			
			return String.Format("{0}&{1}={2}", errorPageUrl, errorMessageParamName, HttpUtility.UrlEncode(message));
		}
	}
}
